<template>
    <div ref="barChart" class="bar-chart"></div>
</template>

<script>
  import * as echarts from 'echarts';

  export default {
    name: 'BarChart',
    props: {
      chartData: {
        type: Array,
        required: true,
      },
    },
    mounted() {
      this.initChart();
      window.addEventListener('resize', this.resizeChart); // 监听窗口大小变化
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.resizeChart);
    },
    methods: {
      initChart() {
        const chartDom = this.$refs.barChart;
        const myChart = echarts.init(chartDom);
        const option = {
          title: {
            text: '分布统计',
            left: 'center',
          },
          tooltip: {},
          xAxis: {
            type: 'category',
            data: this.chartData.map(item => item.label),
            axisLabel: {
              interval: 0,
            },
            axisTick: {
              show: false,
            },
          },
          yAxis: {
            type: 'value',
          },
          series: [
            {
              name: '数量',
              type: 'bar',
              data: this.chartData.map(item => item.value),
              itemStyle: {
                color: '#4CAF50',
              },
            },
          ],
        };
        myChart.setOption(option);
      },
      resizeChart() {
        const chartDom = this.$refs.barChart;
        if (chartDom) {
          echarts.getInstanceByDom(chartDom).resize();
        }
      },
    },
  };
</script>

<style scoped>
    .bar-chart {
        height: 550px; /* 你可以根据需要调整高度 */
    }
</style>
